import Vue from 'vue';
import ViewUI from 'view-design';
import Util from '../libs/util';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import { routers } from './router';
import MedicalRecord from '@/views/medical/MedicalRecord.vue';

Vue.use(VueRouter);
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}

const RouterConfig = {
  mode: 'history',
  routes: routers
};

export const router = new VueRouter(RouterConfig);

router.beforeEach((to, from, next) => {
    ViewUI.LoadingBar.start();
    Util.title(to.meta.title);
    const token = Cookies.get('ZWZ_TOKEN');
    
    if (!token && to.name !== 'login' && to.name !== 'regist') { // 未登录且要跳转的页面不是登录页和注册页
        next({
            name: 'login'
        });
    } else if (!token && (to.name === 'login' || to.name === 'regist')) { // 未登陆且要跳转的页面是登录页或注册页
        next();
    } else if (token && to.name === 'login') { // 已登录且要跳转的页面是登录页
        next({
            name: 'home'
        });
    } else {
        if (token) {
            next();
        } else {
            next({
                name: 'login'
            });
        }
    }
});

router.afterEach(() => {
    ViewUI.LoadingBar.finish();
    window.scrollTo(0, 0);
});
